package com.lagou.edu.service.impl;

import com.lagou.edu.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
@Service
@RefreshScope
public class MailServiceImpl implements MailService {

    @Value("${lagou.mail.host}")
    private String host;
    @Value("${lagou.mail.port}")
    private String port;
    @Value("${lagou.mail.username}")
    private String username;
    @Value("${lagou.mail.password}")
    private String password;

    @Override
    public boolean sendMail(String mailAddress, String subject, String code) {
        String content = "本次验证码: " + code;
        log.info("给用户:{}, 发送验证码:{}, 发件邮箱:{}", mailAddress, code, username);
        doSendMailAsync(mailAddress, subject, content);
        return true;
    }

    @Async
    public void doSendMailAsync(String mailAddress, String subject, String content) {
        log.info("prepare send mail: to: ({}) , title : ({}) , content : ({})",mailAddress, subject, content);
        String senderEmail = username;
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.auth", "true");

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setJavaMailProperties(properties);
        javaMailSender.setHost(host);
        javaMailSender.setPort(Integer.valueOf(port));
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");//解决附件乱码
            mimeMessageHelper.setTo(mailAddress);
            mimeMessageHelper.setFrom(senderEmail);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);

            log.info("send mail: to: ({}) , title : ({}) , content : ({})", mailAddress, subject, content);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.warn("send mail error:", e);
        }
    }
}
